package dev.ece.util.tools;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import dev.ece.util.lib.Vector3f;

public class NormalUtils {

	/**
	 * 计算向量
	 * @param from 起始点
	 * @param to 终点
	 * @return 从from指向to的向量
	 */
	public static Vector3f buildVector(Vector3f from, Vector3f to, Vector3f result) {
		if(result == null) {
			result = new Vector3f();
		}
		result.splus(from, to);
		result.normalize();
		return result;
	}
	
	/**
	 * 计算法线
	 * @param v1 向量1
	 * @param v2 向量2
	 * @return
	 */
	public static Vector3f buildNormal(Vector3f v1, Vector3f v2, Vector3f result) {
		if(result == null) {
			result = new Vector3f();
		}
		Vector3f normal = Vector3f.cross(v1, v2);
		result.set(normal.getX(), normal.getY(), normal.getZ());
		result.normalize();
		return result;
	}
	
	/**
	 * 根据由3个点形成的平面计算法线，点顺序需要逆时针
	 * @param p1 点1
	 * @param p2 点2 计算他的法线
	 * @param p3 点3
	 * @return
	 */
	public static Vector3f buildNormal(Vector3f p1, Vector3f p2, Vector3f p3, Vector3f result) {
		return buildNormal(buildVector(p1, p2, null), buildVector(p2, p3, null), result);
	}
	
	/**
	 * 根据5个点技术点法线
	 * @param c 中心点，计算它的法线
	 * @param n 北顶点
	 * @param e 东顶点
	 * @param s 南顶点
	 * @param w 西顶点
	 * @param result 法线
	 * @return 法线
	 */
	public static Vector3f buildNormal(Vector3f c, Vector3f n, Vector3f w, Vector3f s, Vector3f e, Vector3f result) {
		if(result == null) {
			result = new Vector3f();
		}
		result.set(0, 0, 0);
		List<Vector3f> list = new ArrayList<Vector3f>();
		Vector3f normal = null;
		if(n != null && e != null) {
			normal = buildNormal(n, c, e, null);
			normal.normalize();
			if(!list.contains(normal)) {
				list.add(normal);
			}
		}
		if(e != null && s != null) {
			normal = buildNormal(e, c, s, null);
			normal.normalize();
			if(!list.contains(normal)) {
				list.add(normal);
			}
		}
		if(s != null && w != null) {
			normal = buildNormal(s, c, w, null);
			normal.normalize();
			if(!list.contains(normal)) {
				list.add(normal);
			}
		}
		if(w != null && n != null) {
			normal = buildNormal(w, c, n, null);
			normal.normalize();
			if(!list.contains(normal)) {
				list.add(normal);
			}
		}
		Iterator<Vector3f> it = list.iterator();
		while(it.hasNext()) {
			normal = it.next();
			result.add(normal);
			result.normalize();
		}
		return result;
	}
	
}
